package hoangbn.apps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;

import com.google.android.gms.maps.model.LatLng;

public class JSONParser {
	public JSONParser() {
	}

	public String getJSONFromUrl(LatLng start, LatLng end)
			throws ClientProtocolException, IOException, JSONException {
		// Create a new client object
		String url = "http://maps.googleapis.com/maps/api/directions/json?"
				+ "origin=" + start.latitude + "," + start.longitude
				+ "&destination=" + end.latitude + "," + end.longitude
				+ "&sensor=false";

		HttpClient httpcClient = new DefaultHttpClient();
		// Now POST to url ( we could also use a GET )
		HttpPost httpPost = new HttpPost(url);
		// Execute the POST (GET) the response
		HttpResponse response = httpcClient.execute(httpPost);
		// Get the message from the response
		HttpEntity entity = response.getEntity();
		// Get the content of the message
		InputStream is = entity.getContent();

		// Convert response to String
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				"UTF-8"), 8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		reader.close();

		return sb.toString();
	}
}
